﻿using DevExpress.Images;
using DevExpress.XtraGrid.Views.Grid;
using System;
using System.Linq;

namespace Inaction.UI.Extensions.ControlExtensions.Grid
{
    internal class FooterHelper
    {
        public static void Extend(GridView gridView)
        {
            gridView.PopupMenuShowing += new PopupMenuShowingEventHandler(gridView_PopupMenuShowing);
        }

        static void gridView_PopupMenuShowing(object sender, PopupMenuShowingEventArgs e)
        {
            if (e.HitInfo.Column == null) return;
            var view = sender as GridView;
            if (view == null) return;
            var itemShowFooter = e.Menu.Items.Cast<DevExpress.Utils.Menu.DXMenuItem>().FirstOrDefault(p => p.Caption == "显示页脚");

            if (itemShowFooter == null)
            {
                itemShowFooter = new DevExpress.Utils.Menu.DXMenuItem("显示页脚");
                itemShowFooter.Image = Properties.Resources.ShowFooter;
                itemShowFooter.Tag = sender;
                e.Menu.Items.Insert(0, itemShowFooter);
                itemShowFooter.Click += new EventHandler(ShowFooter_Click);
            }
            itemShowFooter.Visible = !view.OptionsView.ShowFooter && e.HitInfo.InColumn;
            var itemHideFooter = e.Menu.Items.Cast<DevExpress.Utils.Menu.DXMenuItem>().FirstOrDefault(p => p.Caption == "隐藏页脚");
            if (itemHideFooter == null)
            {
                itemHideFooter = new DevExpress.Utils.Menu.DXMenuItem("隐藏页脚");
                itemHideFooter.Image = Properties.Resources.HideFooter;
                itemHideFooter.Tag = sender;
                e.Menu.Items.Insert(0, itemHideFooter);
                itemHideFooter.Click += new EventHandler(HideFooter_Click);
            }
            itemHideFooter.Visible = view.OptionsView.ShowFooter && e.HitInfo.InColumn;
        }

        static void ShowFooter_Click(object sender, EventArgs e)
        {
            var item = sender as DevExpress.Utils.Menu.DXMenuItem;
            var view = item.Tag as GridView;
            view.OptionsView.ShowFooter = true;
        }
        static void HideFooter_Click(object sender, EventArgs e)
        {
            var item = sender as DevExpress.Utils.Menu.DXMenuItem;
            var view = item.Tag as GridView;
            view.OptionsView.ShowFooter = false;
        }
    }
}
